#include "StdAfx.h"
#include <Engine/IEngine.h>
#include <Engine/IRenderer.h>
#include <Engine/GlobalEnv.h>
#include <Engine/Math/Vec4.h>
#include <Engine/Math/Mat44.h>
#include <Engine/Math/Math.h>
#include <Engine/ITimer.h>
#include "InputListener.h"
#include "TestFunction.h"

using namespace fastbird;

typedef LRESULT (CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM);

GlobalEnv* g_Env=0;

void UpdateFrame()
{
	g_Env->pTimer->Tick();
	g_Env->pEngine->UpdateFrame(g_Env->pTimer->GetDeltaTime());	
}

void RunGame()
{
	MSG msg={};
	while(msg.message != WM_QUIT)
	{
		if (PeekMessage( &msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			UpdateFrame();
		}
	}
}

LRESULT CALLBACK WinProc( HWND window, UINT msg, WPARAM wp, LPARAM lp )
{
	switch(msg)
	{
	case WM_CLOSE:
		{
			PostQuitMessage(0);
		}
		break;

	}
	g_Env->pEngine->WinProc(window, msg, wp, lp);
	

	return DefWindowProc(window, msg, wp, lp);
}

#include <limits>
#undef max
#undef min

int main()
{
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

	std::vector<int> test;
	test.push_back(0);
	test.push_back(0);
	
	std::string dllName;
	dllName = "./Engine";
#ifdef _DEBUG 
	dllName +="_Debug";
#endif
	dllName += ".dll";
	HINSTANCE hDLL = LoadLibrary(dllName.c_str());
	if (!hDLL)
	{
		assert(0);
	}
	else
	{
		typedef fastbird::IEngine* (_cdecl *CREATE_ENGINE_PROC)(void);
		CREATE_ENGINE_PROC CreateEngineProc = (CREATE_ENGINE_PROC)GetProcAddress(hDLL, "CreateEngine");
		if (CreateEngineProc == 0)
		{
			assert(0);
		}
		else
		{
			{
				fastbird::EnginePtr pEngine = CreateEngineProc();
				pEngine->GetGlobalEnv(&g_Env);

				// Init Window
				int x = GetSystemMetrics(SM_XVIRTUALSCREEN);
				int y = GetSystemMetrics(SM_YVIRTUALSCREEN);
				HWND hWnd = pEngine->CreateEngineWindow(x, y, 1024, 768, "GeoMorphing", WinProc);
				if(hWnd)
					ShowWindow( hWnd, SW_SHOWDEFAULT );

				// Init DirectX
				bool success = pEngine->InitEngine(fastbird::IEngine::D3D11);

				// CreateTerrain
				pEngine->CreateTerrain(1025, 1025, 1.0f, "Data/height.png");
				pEngine->GetRenderer()->SetWireframe(false);


				

				
				if(hWnd && success)
				{
					ShowWindow( hWnd, SW_SHOWDEFAULT ) ;
					RunGame();
				}

			}
			
			FreeLibrary(hDLL);
		}
	}
}




// CreateRenderResources

// Update/Loop

// ClearRenderResources

// Release DirectX

// Delete Window